package com.ccsoft.atools.security;

import com.ccsoft.atools.model.SysPermission;
import com.ccsoft.atools.model.SysUser;
import com.ccsoft.atools.model.UserFuse;
import com.ccsoft.atools.service.SysUserService;
import com.ccsoft.atools.utils.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:MyUserDetailsService
 * @Description:TODO
 * @Author:chanchaw
 * @Date:2019-11-25 16:11
 * @Version:1.0
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || username.length() <= 0) throw new BusinessException("登录的用户不可为空！");
        SysUser sysUser = sysUserService.selectByUserId(username);// 查询获取用户信息
        if (sysUser == null) throw new BusinessException("未查询到该用户！");

        // 方法 selectPermissionsByUserId 要自己手动写 - 不是 Mybatis-Generator 生成的
        // 获取指定用户拥有的所有权限，权限类 SysPermission 要求实现 SpringSecurity5 的GrantedAuthority
        List<SysPermission> list = sysUserService.selectPermissionsByUserId(username);
        // 实现了接口 UserDetails 的用户类
        // 下面要做两步：
        // 1. 将原始用户类对象赋值给该融合类
        // 2. 给该融合类中的权限赋值
        UserFuse user = new UserFuse();
        user.setSysUser(sysUser);

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        if (list.size() > 0) {
            for (SysPermission item : list) {
                authorities.add(new SimpleGrantedAuthority(item.getPermissionid()));
//                authorities.add(new SimpleGrantedAuthority(item.getUrl()));
            }
            user.setAuthorities(authorities);
            System.out.println("用户" + username + "拥有的权限是：" + user.getAuthorities().toString());
        } else {
            throw new BusinessException("该用户无任何权限，不可登录！");
        }

        return user;
    }
}
